package com.ss.SmartStock.rocketmq;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.concurrent.TimeUnit;

public class Producer {
    public static void main(String[] args) throws Exception {
        timeMessage("topic_1","测试");
    }


    public static void timeMessage(String Topic, String message) throws Exception {
        //1.创建消息生产者producer，并制定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("my-group");
        //2.指定Nameserver地址
        producer.setNamesrvAddr(MqConstant.NAME_SERVER_ADDRESS);
        //3.启动producer
        producer.start();

        //4.创建消息对象，指定主题Topic、Tag和消息体
        /**
         * 参数一：消息主题Topic
         * 参数二：消息Tag
         * 参数三：消息内容
         */
        Message msg = new Message(Topic, "Tag2", message.getBytes(RemotingHelper.DEFAULT_CHARSET));

        //5.发送异步消息
        producer.send(msg, new SendCallback() {
            /**
             * 发送成功回调函数
             * @param sendResult
             */
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送结果：" + sendResult);
            }

            /**
             * 发送失败回调函数
             * @param e
             */
            @Override
            public void onException(Throwable e) {
                System.out.println("发送异常：" + e);
            }
        });

        //线程睡1秒
        TimeUnit.SECONDS.sleep(1);

        //6.关闭生产者producer
        producer.shutdown();


    }


}
